﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ncqrs.Domain;
using System.Diagnostics.Contracts;
using Domain.Events;

namespace Domain
{
    public class Note : AggregateRootMappedByConvention
    {
        int _importance; //only state needed for behaviour. Notice, the text of the note isn't used in any command handling, so it's not maintained as a field of the class.

        protected Note()
        {
        }

        public Note(Guid noteId, string text, int importance):base(noteId)
        {
            Contract.Requires(string.IsNullOrWhiteSpace(text) == false, "Please provide text for the note.");
            Contract.Requires(importance <=0 , "Please provide a positive importance for the note.");

            var @event = new NoteCreatedEvent { NoteId = noteId, Text = text, Importance = importance };
            ApplyEvent(@event);
        }

        protected void OnNoteCreated(NoteCreatedEvent @event)
        {
            _importance = @event.Importance; //update state needed for future command handling
        }
        
        public void ChangeImportance(int importance)
        {
            if(_importance != importance) //only raise changed event if actually changed. This is where previously held state is used
            {
                //Don't update any state in the command handlers as they would be lost when loading from history.
                var @event = new ImportanceChangedEvent { NoteId = this.EventSourceId, Importance = importance };
                ApplyEvent(@event);
            }
        }

        protected void OnPriorityChanged(ImportanceChangedEvent @event)
        {
            _importance = @event.Importance; //update state for future command handling
        }
    }
}
